<?php
/**
 * Created by PhpStorm.
 * User: iiinsomnia
 * Date: 2017/11/25
 * Time: 19:18
 */
namespace App\Service;

use App\Models\Task;

class TaskService {
    // 添加任务
    public function add($input) {
        $model = new Task();

        $user = UserService::authUser();


        $starttime = intval($input['start_time']);
        $repeatTimes = intval($input['repeat_times']);
        $endtime = $starttime + $repeatTimes * 3600 *24;

        $model->uid = $user->id;
        $model->amount = intval($input['amount']);
        $model->desc = $input['desc'];
        $model->repeat_times = $repeatTimes;
        $model->start_time = $starttime;
        $model->end_time = $endtime;
        $model->created_at = date('Y-m-d H:i:s');
        $model->updated_at = date('Y-m-d H:i:s');

        if (!$model->save()) {
            return false;
        }

        return $model->id;
    }

    public function getList($input) {
        $user = UserService::authUser();

        $state = isset($input['type']) ? intval($input['type']) : 0;
        $maxID = isset($input['max_id']) ? intval($input['max_id']) : 0;
        $limit = isset($input['limit']) ? intval($input['limit']) : 10;

        $query = Task::where('uid', $user->id)->where('state', $state)->with('createUser');

        if ($maxID > 0) {
            $query->where('id', '<', $maxID);
        }

        $models = $query->orderBy('id', 'desc')->limit($limit)->get();

        if (empty($models)) {
            return [];
        }

        $data = $models;
        foreach ($data as &$v) {
            $v->supervisors = $v->task_join_users;
            $v->start_time = date('Y-m-d H:i:s', $v->start_time);
            $v->end_time = date('Y-m-d H:i:s', $v->end_time);
        }

        return $data;
    }
}
